package com.example.choupaiapp.main.activity.home;

import android.Manifest;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.example.choupaiapp.R;
import com.example.choupaiapp.common.adapter.BaseAdapterHelper;
import com.example.choupaiapp.common.adapter.QuickAdapter;
import com.example.choupaiapp.common.ui.activity.CommonActivity;
import com.example.choupaiapp.common.util.ContextUtil;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.main.bean.HomeLocationBean;
import com.example.choupaiapp.main.bean.HomeLocationData;
import com.example.choupaiapp.main.bean.PublishLocationBean;
import com.example.choupaiapp.main.bean.PublishLocationData;
import com.example.choupaiapp.main.util.LocationUtil;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ASUS on 2019/11/4.
 */

public class LocationActivity extends CommonActivity implements PoiSearch.OnPoiSearchListener, OnRefreshLoadMoreListener, AMapLocationListener {

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.right_tv)
    TextView rightTv;
    @BindView(R.id.location_tv)
    TextView locationTv;
    @BindView(R.id.listview)
    ListView listview;
    private String city;
    private String citycode;
    private double lat;
    private double lot;
    private String aoiName;
    private QuickAdapter<PoiItem> quickAdapter;
    private int pageSize = 20;
    private int pageNum = 1;
    private AMapLocation mAMapLocation;
    private String flag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void OnMessageEvent(String event) {
        if (event.contains("city")) {
            EventBus.getDefault().post("finish_location_search");
            city = event.split(":")[1];
            rightTv.setText(city);

            pageNum = 1;

            LocationUtil.getInstance().searchPoiOption(city, "", this, 0, 0, 0);
            LocationUtil.getInstance().setQuery(pageNum++, pageSize);
            LocationUtil.getInstance().searchPoi();
        } else if ("finish_location".equals(event)) {
            Logger.e("finish_location*********");
            finishActivity();
        }
    }

    @Override
    protected void initView() {
        setTitle("选择地址");
        EventBus.getDefault().register(this);
        refreshLayout.setOnRefreshLoadMoreListener(this);
        refreshLayout.setRefreshHeader(new MaterialHeader(context).setColorSchemeResources(R.color.common_color));
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableLoadMore(false);

        quickAdapter = new QuickAdapter<PoiItem>(context, R.layout.item_loaction) {
            @Override
            protected void convert(BaseAdapterHelper helper, PoiItem item) {
                helper.setText(R.id.location, item.getTitle());
                helper.setText(R.id.address, item.getSnippet());
            }
        };

        listview.setAdapter(quickAdapter);

        listview.setOnItemClickListener((adapterView, view, i, l) -> {
            if ("home".equals(flag)) {
                HomeLocationBean homeLocationBean = new HomeLocationBean();
                homeLocationBean.setItem(quickAdapter.getItem(i));
                EventBus.getDefault().post(homeLocationBean);
                MobclickAgent.onEvent(ContextUtil.getContext(), "selectAddressID");
            } else if ("publish".equals(flag)) {
                PublishLocationBean publishLocationBean = new PublishLocationBean();
                publishLocationBean.setItem(quickAdapter.getItem(i));
                EventBus.getDefault().post(publishLocationBean);
            }
            finishActivity();
        });

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            flag = bundle.getString("flag");
            city = bundle.getString("city");
            citycode = bundle.getString("citycode");
            lat = bundle.getDouble("lat");
            lot = bundle.getDouble("lot");
            aoiName = bundle.getString("aoiName");

            rightTv.setText(city);
        } else {
            rightTv.setText("定位失败");
        }

        locationTv.setText("定位中...");
        if (rxPermissions.isGranted(Manifest.permission.ACCESS_COARSE_LOCATION) && rxPermissions.isGranted(Manifest.permission.ACCESS_FINE_LOCATION)
                && rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE) && rxPermissions.isGranted(Manifest.permission.READ_EXTERNAL_STORAGE)
                && rxPermissions.isGranted(Manifest.permission.READ_PHONE_STATE)) {

            LocationUtil.getInstance().locationOption();
            LocationUtil.getInstance().setLocationListener(this);
            LocationUtil.getInstance().startLocation();
        } else {
            rxPermissions.request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE).subscribe(aBoolean -> {
                if (aBoolean) {
                    LocationUtil.getInstance().locationOption();
                    LocationUtil.getInstance().setLocationListener(LocationActivity.this);
                    LocationUtil.getInstance().startLocation();
                } else {
                    showImageToas("拒绝定位权限 无法获取定位");
                }
            });
        }
    }

    @Override
    protected void initData() {


    }

    @OnClick({R.id.right_tv, R.id.search_location, R.id.refresh_location, R.id.location_rl})
    public void onViewClicked(View view) {
//        super.onViewClicked(view);
        if (Utils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.right_tv:
                if (!rightTv.getText().toString().equals("定位失败")) {
                    Bundle bundle = new Bundle();
                    bundle.putString("city", city);
                    startActivity(LocationCityActivity.class, bundle);
                } else {
                    startActivity(LocationCityActivity.class);
                }
                break;
            case R.id.search_location:
                if (mAMapLocation != null) {
                    Bundle bundle = new Bundle();
                    bundle.putString("flag", flag);
                    bundle.putString("citycode", mAMapLocation.getCityCode());
                    bundle.putDouble("lat", mAMapLocation.getLatitude());
                    bundle.putDouble("lot", mAMapLocation.getLongitude());
                    startActivity(SearchLocationActivity.class, bundle);
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString("flag", flag);
                    bundle.putString("citycode", citycode);
                    bundle.putDouble("lat", lat);
                    bundle.putDouble("lot", lot);
                    startActivity(SearchLocationActivity.class, bundle);
                }
                break;
            case R.id.location_rl:
//                finishActivity();
                if (mAMapLocation != null) {
                    if ("home".equals(flag)) {
                        HomeLocationData homeLocationBean = new HomeLocationData();
                        homeLocationBean.setTitle(locationTv.getText().toString());
                        homeLocationBean.setCity(city);
                        homeLocationBean.setProvice(mAMapLocation.getProvince());
                        homeLocationBean.setLat(mAMapLocation.getLatitude());
                        homeLocationBean.setLon(mAMapLocation.getLongitude());
                        homeLocationBean.setDis(mAMapLocation.getDistrict());
                        EventBus.getDefault().post(homeLocationBean);
                        MobclickAgent.onEvent(ContextUtil.getContext(), "selectAddressID");
                    } else if ("publish".equals(flag)) {
                        PublishLocationData publishLocationBean = new PublishLocationData();
                        publishLocationBean.setTitle(locationTv.getText().toString());
                        publishLocationBean.setCity(city);
                        publishLocationBean.setProvice(mAMapLocation.getProvince());
                        publishLocationBean.setLat(mAMapLocation.getLatitude());
                        publishLocationBean.setLon(mAMapLocation.getLongitude());
                        publishLocationBean.setDis(mAMapLocation.getDistrict());
                        publishLocationBean.setAdCode(mAMapLocation.getAdCode());
                        publishLocationBean.setAddress(mAMapLocation.getAddress());
                        publishLocationBean.setStreet(mAMapLocation.getStreet());
                        EventBus.getDefault().post(publishLocationBean);
                    }
                    finishActivity();
                } else {
                    showImageToas("正在获取定位数据中");
                }

                break;
            case R.id.refresh_location:
                break;
        }
    }

    @Override
    public void onPoiSearched(PoiResult poiResult, int i) {
        if (i == 1000 && poiResult != null && poiResult.getPois().size() > 0) {
            if (pageNum == 2) {
                quickAdapter.clear();
            }
            quickAdapter.addAll(poiResult.getPois());
            quickAdapter.notifyDataSetChanged();
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
        } else {
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
            showImageToas("附近暂无数据");
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        LocationUtil.getInstance().setQuery(pageNum++, pageSize);
        LocationUtil.getInstance().searchPoi();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        pageNum = 1;
        LocationUtil.getInstance().setQuery(pageNum++, pageSize);
        LocationUtil.getInstance().searchPoi();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                mAMapLocation = aMapLocation;
                //可在其中解析amapLocation获取相应内容。
//                aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
//                aMapLocation.getLatitude();//获取纬度
//                aMapLocation.getLongitude();//获取经度
//                aMapLocation.getAccuracy();//获取精度信息
//                aMapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
//                aMapLocation.getCountry();//国家信息
//                aMapLocation.getProvince();//省信息
//                aMapLocation.getCity();//城市信息
//                aMapLocation.getDistrict();//城区信息
//                aMapLocation.getStreet();//街道信息
//                aMapLocation.getStreetNum();//街道门牌号信息
//                aMapLocation.getCityCode();//城市编码
//                aMapLocation.getAdCode();//地区编码
//                aMapLocation.getAoiName();//获取当前定位点的AOI信息
//                aMapLocation.getBuildingId();//获取当前室内定位的建筑物Id
//                aMapLocation.getFloor();//获取当前室内定位的楼层
//                aMapLocation.getGpsAccuracyStatus();//获取GPS的当前状态
//                //获取定位时间
//                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                Date date = new Date(aMapLocation.getTime());
//                df.format(date);

                Logger.e(aMapLocation.getLatitude() + "---" +
                        aMapLocation.getLongitude() + "---" +
                        aMapLocation.getAddress() + "---" +
                        aMapLocation.getDistrict() + "---" +
                        aMapLocation.getStreet() + "---" +
                        aMapLocation.getStreetNum() + "---" +
                        aMapLocation.getAoiName() + "---" +
                        aMapLocation.getPoiName() + "---" +
                        aMapLocation.getBuildingId() + "---" +
                        aMapLocation.getFloor() + "---" +
                        aMapLocation.getDescription());

                locationTv.setText(aMapLocation.getAoiName().equals("") ? aMapLocation.getPoiName() : aMapLocation.getAoiName());
                city = aMapLocation.getCity();
                rightTv.setText(city);

                pageNum = 1;
                LocationUtil.getInstance().searchPoiOption(aMapLocation.getCity(), aMapLocation.getCityCode(), this, 10000, aMapLocation.getLatitude(), aMapLocation.getLongitude());
                LocationUtil.getInstance().setQuery(pageNum++, pageSize);
                LocationUtil.getInstance().searchPoi();

                refreshLayout.setEnableRefresh(true);
                refreshLayout.setEnableLoadMore(true);

                LocationUtil.getInstance().stopLocation();//停止定位后，本地定位服务并不会被销毁
            } else {
                //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                Logger.e("AmapError--" + "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
                showImageToas("定位失败");
                locationTv.setText("无法获取位置");
            }
        }
    }
}
